package com.huanghuai.config;

import com.huanghuai.filter.ValidateCodeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@EnableGlobalMethodSecurity(prePostEnabled = true)//开启全局方法安全 启用预授权注解和后授权注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private AppAuthenticationSuccessHandler successHandler;

    @Resource
    private AppAuthenticationFailHandler failHandler;

    @Resource
    private AppLogoutSuccessHandler logoutSuccessHandler;

    @Resource
    private ValidateCodeFilter validateCodeFilter;

    @Resource
    private AppAccessDeniedHandler deniedHandler;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //在用户名密码认证过滤器前添加图片验证码过滤器
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class);
        http.authorizeRequests()//授权请求
                .mvcMatchers("/code/image")
                .permitAll()//放开验证码的请求
                .mvcMatchers("/student/**")//匹配这个url
                .hasAnyAuthority("student:add")//拥有这个权限的用户可以访问的/student/**
                //判断是否有权限
                .mvcMatchers("/teacher/**")
                .hasAnyAuthority("teacher:query")//拥有这个权限的用户可以访问的/teacher/**
                .anyRequest() //任何请求
                .authenticated();//都需要登录，注意：没有配置mvc的只要登录成功就可以访问
        http.formLogin()
                .loginPage("/toLogin")//配置登录页面
                .usernameParameter("uname")//配置用户名参数
                .passwordParameter("pwd")//配置密码参数
                .loginProcessingUrl("/login/doLogin")
                .failureForwardUrl("/toLogin")//登录失败
                .successForwardUrl("/index/toIndex")//登录成功
//                .successHandler(successHandler)//配置认证成功处理器
                .failureHandler(failHandler)//配置认证失败处理器
                .permitAll(); //允许表单登录 permit：允许
        http.logout().logoutSuccessUrl("/toLogin");//配置退出成功登录页面
        http.csrf().disable();//关闭跨域请求保护
//        http.exceptionHandling().accessDeniedHandler(deniedHandler);//配置拒绝访问处理器
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
